package com.atguigu.controller;

import com.atguigu.common.result.R;
import com.atguigu.service.MsmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        //进行非空校验
        if(StringUtils.isEmpty(phone)){
            return  R.error().message("手机号不能为空");
        }
        //在有效期内，验证码不能重复发送  (验证码从redis中拿)
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code))
            return R.ok().message("验证码已经发送");
        //生成验证码 创建一个随机code
        //*10000是取四位整数
        code = (long) (new Random().nextDouble() * 10000) + "";
        //调用方法发送
        boolean isSend = msmService.send(phone, code);
        if(isSend) {
            //发送成功，验证码放到redis，设置有效时间  存储五分钟
            redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("发送短信失败");
        }
    }
}